﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using vuonthieunhi.Models;
namespace vuonthieunhi.Areas.Administration.Models
{
    public class AuthenticateDao : BaseDao
    {
        public UserAdmin GetUserById(int userId)
        {
            return dbContext.UserAdmins.FirstOrDefault(usr => usr.UserAdminId == userId && usr.DeleteFlag == false);
        }

        public UserAdmin GetUserByName(string username)
        {
            return dbContext.UserAdmins.FirstOrDefault(user => user.UserName.Equals(username) && user.DeleteFlag == false);
        }

        /// <summary>
        /// Check Permission
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="moduleId"></param>
        /// <param name="permissionIds"></param>
        /// <returns></returns>
        public bool CheckPermission(int userId, byte moduleId, int[] permissionIds)
        { 
            var user = GetUserById(userId);

            if (user == null)
            {
                return false;
            }

            List<int> groupIds = user.User_Groups.Select(c => c.GroupId).ToList<int>();            

            IEnumerable<GroupPermission> userModFuncs = dbContext.GroupPermissions.Where(c => groupIds.Contains(c.GroupId) && c.ModuleId == moduleId && permissionIds.Contains(c.PermissionId) && c.Group.IsActive == true);

            if (userModFuncs.Count() == 0)
            {
                return false;
            }

            return true;             
        }
    }
}